package com.truongnha.clienttn.presentation;

//import org.json.JSONArray;

import com.truongnha.clienttn.R;
import com.truongnha.clienttn.business.service.LoginService;
import com.truongnha.clienttn.business.service.LogoutService;
import com.truongnha.clienttn.business.service.SavedAccountService;
import com.truongnha.clienttn.business.model.SavedAccountModel;
import com.truongnha.clienttn.business.model.UserModel;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {
	private LoginService loginService;
	private UserModel user;
	private SavedAccountModel savedAccountModel;
	private EditText username;
	private EditText password;
	private Button btnLogin;
	private TextView loginErrorMsg;
	private boolean error = false;
	private CheckNetwork checkNetwork;
	private boolean isSavedAccount = false;

	private void displayNoNetwork() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Bạn có muốn thử lại không ?")
				.setCancelable(true)
				.setIcon(R.drawable.alert_icon)
				.setTitle("Không thể kết nối internet!")
				.setPositiveButton("Không", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						finish();
					}
				})
				.setNegativeButton("Có",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// dialog.cancel();
								finish();
								Intent i = new Intent(getApplicationContext(),
										LoginActivity.class);
								startActivity(i);
								finish();
							}
						});
		AlertDialog alert = builder.create();
		alert.getWindow().getAttributes().windowAnimations = R.style.DialogAnimationTopDown;
		alert.show();
	}

	void checkSavedAccount() {
		// Check remember table for previous user
		SavedAccountService savedAccountService = new SavedAccountService(
				getApplication());
		savedAccountModel = savedAccountService.get();
		isSavedAccount = savedAccountModel != null;
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		username = (EditText) findViewById(R.id.username);
		password = (EditText) findViewById(R.id.password);

		btnLogin = (Button) findViewById(R.id.btnLogin);
		loginErrorMsg = (TextView) findViewById(R.id.loginErrorMsg);

		class loginTask extends AsyncTask<String, Void, Void> {
			ProgressDialog dialog;

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				Log.d("Task", "onPreExecute");
				dialog = new ProgressDialog(LoginActivity.this);
				dialog.setMessage("Đang kết nối...");
				dialog.show();
				Log.d("Task", "onPreExecute");
			}

			private void saveAccountToDatabase() {
				SavedAccountService savedAccountService = new SavedAccountService(
						getApplicationContext());
				savedAccountService.save(username.getText().toString(),
						password.getText().toString());
			}

			@Override
			protected Void doInBackground(String... params) {
				Log.d("Task", "doInBackground");
				if (isSavedAccount) {
					loginService = new LoginService(getApplicationContext(),
							savedAccountModel.getUsername(),
							savedAccountModel.getPassword());
				} else {
					loginService = new LoginService(getApplicationContext(),
							username.getText().toString(), password.getText()
									.toString());
				}
				if (checkNetwork.isAvailable())
					loginService.login();
				else
					loginService.setSuccess(true);
				publishProgress();
				// check for login response

				if (loginService.isSuccess()) {
					if (!isSavedAccount)
						saveAccountToDatabase();
					user = loginService.getUser();
					if (user.getPosition().equals("STUDENT")) {
						Intent i = new Intent(getApplicationContext(),
								MainScreenActivity.class);
						startActivity(i);
						finish();
					} else if (user.getPosition().equals("TEACHER")) {
						Intent i = new Intent(getApplicationContext(),
								MainScreenActivity.class);
						startActivity(i);
						finish();
					}
				} else {
					Log.e("LOG", "login fault");
					error = true;
				}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				Log.d("Task", "onPostExecute");
				if (dialog.isShowing()) {
					dialog.dismiss();
				}
				if (error) {
					loginErrorMsg.setText(R.string.loginErrorMsg);
				}
				Log.d("Task", "onPostExecute");
			}

			@Override
			protected void onProgressUpdate(Void... values) {
				super.onProgressUpdate(values);
				dialog.setMessage("Đang tải...");
			}
		}// end LoginAsyncTask

		// //////////////////////////////////////////////////
		// //////////////////////////////////////////////////
		class CheckNetworkTask extends AsyncTask<String, Void, Void> {
			ProgressDialog dialog;

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				dialog = new ProgressDialog(LoginActivity.this);
				dialog.setMessage("Đang kiểm tra kết nối internet...");
				dialog.show();
			}

			@Override
			protected Void doInBackground(String... params) {
				checkSavedAccount();
				checkNetwork = new CheckNetwork(getApplicationContext());
				checkNetwork.isAvailable(true);
				Log.d("log saved account", "" + isSavedAccount);
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPostExecute(result);
				if (dialog.isShowing()) {
					dialog.dismiss();
				}
				if (!isSavedAccount) {
					if (!checkNetwork.isAvailable()) {
						displayNoNetwork();
					}
				}

				if (isSavedAccount)
					if (checkNetwork.isAvailable()) {
						LogoutService logoutService = new LogoutService(
								getApplicationContext());
						logoutService.logout(false);

						new loginTask().execute();
					} else {
						new loginTask().execute();
					}
			}

			@Override
			protected void onProgressUpdate(Void... values) {
				Log.d("Task", "onProgressUpdate");
				super.onProgressUpdate(values);
				dialog.setMessage("Đang kiểm tra kết nối internet...");
				Log.d("Task", "onProgressUpdate");
			}
		}// end LoginAsyncTask

		new CheckNetworkTask().execute();
		btnLogin.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				if (checkNetwork.isAvailable()) {
					LogoutService logoutService = new LogoutService(
							getApplicationContext());
					logoutService.logout();
					new loginTask().execute();
				}
			}
		});// End listening

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("exit", "exit");
		finish();
	}

}
